/**
 * @description 下拉框和单选框都有的模板
 * @example 与业绩基准偏移事件
 * @author gf
 */

import styled from "styled-components";
import { Select } from "antd";
import SSelect from "../Select";
import SInputNumber from "../Input/InputNumber";
import { Fragment, useEffect, useState } from "react";
import { RedBtn } from "../Button";
import { BottomCard } from "./BottomCard";
import { RedTitle } from "../Title/redTitile";
import { collectErrors } from "./InlineInput";
import { ToFixNumber } from "@/utils/utils";
import { querySelectCom } from "@/pages/ComParams/service";
import { querySelectSig } from "@/pages/SigFundParams/service";
// 模板外部盒子
export const Box = styled.div`
  width: 100%;
  background: #ffffff;
  border: 1px solid #e4e4e4;
  border-radius: 2px;
  padding: 12px;
  margin-top: 8px;
`;
// 文本样式
export const Text = styled.span`
  font-size: 13px;
  color: #35425e;
  opacity: ${(props) => props.opacity || 1};
`;
// flex布局
export const FlexDiv = styled.div`
  display: flex;
  align-items: center;
  justify-content: ${(props) => props.justify || "unset"};
  margin-top: ${(props) => props.mt || "0"};
  margin-bottom: ${(props) => props.mb || "0"};
`;

const Positive = [
  "deviation_from_benchmark_index_positive", // "各基-与业绩基准正偏移"
  "portfolio_deviation_from_benchmark_positive", // 组合-与业绩基准正偏移
];

const Negative = [
  "deviation_from_benchmark_index_negative", // "各基-与业绩基准负偏移"
  "portfolio_deviation_from_benchmark_negative", // 组合-与业绩基准负偏移
];

// 适合此模板的事件代码
export const EVENT_SELECT_INPUT = [
  ...Positive,
  ...Negative,
  "portfolio_deviation_from_benchmark", // 与业绩基准偏移
];

const SelectInput = (props: any) => {
  const { thresholdValue, onSubmit, eventInfo, enable } = props;
  const [saveParams, setSaveParams] = useState({
    gapDay: "",
    threshold: "",
    benchmarkCode: "",
  });
  const [isChanged, setIsChanged] = useState(false);
  const [errorList, setErrorList] = useState([]);
  const [selectList, setSelectList] = useState<any>([]);

  useEffect(() => {
    setSaveParams({
      gapDay: thresholdValue?.gapDay,
      threshold: thresholdValue?.threshold,
      benchmarkCode: thresholdValue?.benchmarkCode,
    });
    setIsChanged(false);
    if (eventInfo.fundType === "sig") {
      querySelectSig().then((res) => {
        if (res?.code === "0") {
          setSelectList(res?.data);
        }
      });
    } else {
      querySelectCom().then((res) => {
        if (res?.code === "0") {
          setSelectList(res?.data);
        }
      });
    }
    setErrorList([]);
  }, [thresholdValue]);

  const onChange = (val: string, key: string) => {
    handleCollectErrors(val?.toString(), key);
    setIsChanged(true);
    setSaveParams((state) => {
      return {
        ...state,
        [key]: val || "",
      };
    });
  };

  // 收集错误
  const handleCollectErrors = (val?: string, key?: string) => {
    let res: string[] = collectErrors(val, key, errorList, saveParams);
    setErrorList([...new Set(res)]);
    return [...new Set(res)];
  };

  useEffect(() => {
    if (enable !== undefined && enable !== eventInfo?.enable) {
      setIsChanged(true);
    }
  }, [enable]);

  const onClick = () => {
    const res = handleCollectErrors();
    if (errorList.length > 0 || res.length > 0) return;
    onSubmit({
      id: parseFloat(eventInfo.key),
      preValue: saveParams,
      dataMemo: createText(false),
    });
  };
  const createText = (html: Boolean) => {
    // 创建文案
    let str = `<p>* 基金近<em> ${ToFixNumber(
      saveParams.gapDay
    )}日 </em>超额收益率${
      Negative.includes(eventInfo.value) ? "≤" : "≥"
    } <em>${ToFixNumber(saveParams.threshold)}%</em> 。</p>`;
    if (!html) {
      str = str
        .replaceAll("<p>", "")
        .replaceAll("</p>", "")
        .replaceAll("<em>", "")
        .replaceAll("</em>", "")
        .replace(/\s+/g, "");
    }
    return str;
  };

  return (
    <Fragment>
      <Box>
        <FlexDiv>
          <Text style={{ marginRight: 8 }}>业绩比较基准</Text>
          <SSelect
            suffixIcon={<div className="findfit_icon_arrow " />}
            value={saveParams.benchmarkCode}
            onChange={(e) => onChange(e, "benchmarkCode")}
            iserror={errorList.includes("benchmarkCode")}
            allowClear
          >
            {selectList?.map((v) => (
              <Select.Option key={v.benchmarkCode} value={v.benchmarkCode}>
                {v.benchmarkName}
              </Select.Option>
            ))}
          </SSelect>
        </FlexDiv>
        <FlexDiv mt="8px">
          <Text>近</Text>
          <SInputNumber
            value={saveParams.gapDay}
            isError={errorList.includes("gapDay")}
            onChange={(e) => onChange(e, "gapDay")}
            min={0}
            max={1000}
            precision={0}
          />
          <Text>
            {`日超额收益率${Negative.includes(eventInfo.value) ? "≤" : "≥"}`}{" "}
          </Text>
          <SInputNumber
            value={saveParams.threshold}
            isError={errorList.includes("threshold")}
            onChange={(e) => onChange(e, "threshold")}
            precision={6}
            max={9999.999999}
            min={-9999.999999}
          />
          <Text>%</Text>
        </FlexDiv>
        {![
          "portfolio_deviation_from_benchmark_positive",
          "portfolio_deviation_from_benchmark_negative",
        ].includes(eventInfo.value) && <BottomCard info={createText(true)} />}
      </Box>
      <FlexDiv style={{ marginTop: 12, alignItems: "flex-end" }}>
        <RedBtn disabled={!isChanged} onClick={!isChanged ? null : onClick}>
          确定
        </RedBtn>
        {/* 按钮说明文案 */}
        {isChanged && <RedTitle eventInfo={eventInfo} />}
      </FlexDiv>
    </Fragment>
  );
};

export default SelectInput;
